// 这份文件就是用来做拦截的
import axios from 'axios'
const { CONTEST_URL } = require("@/utils/URL");
import store from "@/store/index";
import router from '@/router';
import { toast } from '@/components/toast/index.js'
// 创建一个单例（实例）
const instance = axios.create({
    baseURL: CONTEST_URL,
    timeout: 60000
})

// 拦截器 - 请求拦截
instance.interceptors.request.use(config => {
    // 部分接口需要拿到token
    let token = store.state.token;
    if (token) {
        config.headers = {
            'token': token,
            "Content-Type": "multipart/form-data",
            "Content-Type": "application/json",
        }
    }
    return config;
}, err => {
    return Promise.reject(err)
});


// 拦截器 - 响应拦截
instance.interceptors.response.use(res => {
    if (res.data.resultCode != '200') {
        toast(res.data.message, 2000, 'error');
    }
    if (res.data.resultCode == '1500') {
        this.$store.commit('setRoute', this.$route.path)
        $cookies.remove('token');
        $cookies.remove('nickname');
        $cookies.remove('avatar');
        this.$router.go(0)
    }
    return res;
}, err => {
    toast(err.message, 2000, 'error');
    return Promise.reject(err)
});

// 整体导出
export default instance;